<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use think\Session;
use think\Db;

class Index extends HomeBase {

    public function index() {
        $this->redirect(url('login/index'));
    }

    /* 修改密码 */

    public function password() {
        if ($this->request->isPost()) {
            $post = input('post.');
            if (md5($post['password']) != Session::get('member_info.password')) {
                $this->error('The original password is incorrect');
            }

            $validate_result = $this->validate($post, 'Password');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {

                $status = Db::name('member')->where(['id' => Session::get('member_info.id')])->update(['password' => md5($post['new_password'])]);
                if ($status !== false) {
                    Session::clear();
                    Session::destroy();
                    $this->success('Password successfully changed, please log in again', url('login/index'));
                } else {
                    $this->error('Password modification failed');
                }
            }
        }

        return $this->fetch();
    }

    /* 详情 */

    public function account() {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $result = $this->validate($data, 'Member.' . $data['type']);

            if (true !== $result) {
                $this->error($result);
            } else {
                unset($data['type']);
                Db::name('member')->where(['id' => Session::get('member_info.id')])->update($data);
                $this->success('Information modification success');
            }
        }

        $data['detail'] = Db::name('member')->find(Session::get('member_info.id'));
        $member_level = cache('member_level');
        $data['detail']['level_name'] = $data['detail']['level_id'] ? $member_level[$data['detail']['level_id']]['level_name'] : '';
        $data['addr'] = Db::name('member_addr')->where(['is_default' => 1, 'member_id' => Session::get('member_info.id')])->find();

        return $this->fetch('', ['data' => $data]);
    }

    /* 支付 */

    public function pay() {
        $custom = input('param.custom');  //标识用户的操作 1标识续费

        $level = input('param.level');  //会员重新选择购买

        $is_pay = $this->is_pay($custom, $level);

        return $this->fetch('', ['is_pay' => $is_pay]);
    }

    /* 地址 */

    public function addr() {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $result = $this->validate($data, 'Member.edit3');

            if (true !== $result) {
                $this->error($result);
            } else {
                $memeber_info = Session::get('member_info');
                
                if(Db::name('member_addr')->where(['member_id'=>$memeber_info['id']])->find()){
                    Db::name('member_addr')->where(['member_id' => $memeber_info['id']])->update($data);
                }else{
                    $data['member_id'] = $memeber_info['id'];
                    $data['is_default'] = 1;
                    Db::name('member_addr')->insert($data);
                }
                $this->success('Address modification success');
            }
        }
    }

    /* 证书 */

    public function certificate() {

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $result = $this->validate($data, 'Member.edit4');

            if (true !== $result) {
                $this->error($result);
            } else {
                $data['member_id'] = Session::get('member_info.id');
                Db::name('member_edu_info')->insert($data);
            }
            $this->success('Add success');
        }


        $info = Db::name('member_edu_info')->where(['member_id' => Session::get('member_info.id')])->select();

        $data = Db::name('member')->find(Session::get('member_info.id'));

        return $this->fetch('', ['info' => $info, 'data' => $data]);
    }

    /* 支付记录 */

    public function member() {
        $pay_info = Db::name('member_pay_log')->where(['member_id' => Session::get('member_info.id')])->order('expire_time desc')->select();

        //最后一次购买会员的过期时间提前10天
        $expire_time_10 = '';
        if ($pay_info) {
            $expire_time_10 = strtotime("-10 day", $pay_info[0]['expire_time']);
        }

        return $this->fetch('', ['info' => $pay_info, 'expire_time' => $expire_time_10]);
    }

    /* 选择会员 */

    public function select() {

        $this->assign('member_level', cache('member_level'));

        return $this->fetch();
    }

    /* 联系我们 */

    public function contact() {

        return $this->fetch();
    }

    //该会员是否有选择会员没付款的情况 或者会员到期
    public function is_pay($custom = '', $level = '') {

        $member_level = cache('member_level');

        $member_info = Db::name('member')->find(Session::get('member_info.id'));

        $pay = '';

        if (($member_info && $member_info['level_id'] != 1 && $member_info['pay_status'] == 0 && $member_info['level_status'] == 0) || $custom || $level) {

            $level_name = $level ? $member_level[$level]['level_name'] : $member_level[$member_info['level_id']]['level_name']; //会员名称
            //订单号|会员id|会员名称
            $order_sn = encrypt(strtolower('hj' . substr(md5(uniqid(md5(microtime(true)), true)), 0, 15) . '|' . Session::get('member_info.id')) . '|' . $level_name, 'zhuzong520*');

            //收款账号
//            $payment_account = '332618510-facilitator@qq.com';  //测试账户
            $payment_account = 'elaine@hongjingedu.com';  //真实账户
            //商品价格
//            $goods_price = 0.01;   //测试价格
            $goods_price = $level ? $member_level[$level]['level_price'] : $member_level[$member_info['level_id']]['level_price'];    //真实价格
            //异步通知的链接
            $notify_url = $this->request->domain() . url('login/notify');   //真实付款通知
//            $notify_url =  'http://7rbmrt.natappfree.cc'.url('login/notify'); //测试付款通知
//                        $action = 'https://www.sandbox.paypal.com/cgi-bin/webscr';  //测试付款地址
            $action = 'https://www.paypal.com/cgi-bin/webscr';  //真实付款地址
            //商品名称
            $goods_name = $level ? $member_level[$level]['level_name'] : $member_level[$member_info['level_id']]['level_name'];

            //如果用户是重新选择的会员等级那个获取等级价格  不然就用注册时候选择的等级价格
//            $level = $level ? $member_level[$level]['level_price'] : $member_level[$member_info['level_id']]['level_price'];  
            //取消跳转的链接
            $cancel_return = $this->request->domain() . url('index/cancel');
            //成功跳转的链接
            $suc_url = $this->request->domain() . url('index/suc');

            //自定义参数  用于标识业务逻辑
            $custom = $custom ? $custom : 0;   //1表示续费

            $pay = <<<php
<form id="form_starPay" method="post" name="form_starPay" action="{$action}">
<input value="_xclick" type="hidden" name="cmd"> 
<input value="{$payment_account}" type="hidden" name="business"> 
<input type="hidden" name="custom" value="{$custom}">
<input value="{$goods_name}" type="hidden" name="item_name"> 
<input value="1" type="hidden" name="quantity"> 
<input value="{$goods_price}" type="hidden" name="amount"> 
<input value="USD" type="hidden" name="currency_code"> 
<input value="{$cancel_return}" type="hidden" name="cancel_return"> 
<input value="{$suc_url}" type="hidden" name="return"> 
<input value="{$notify_url}" type="hidden" name="notify_url">
<input type="hidden" name="invoice" value='{$order_sn}'> 
<input value="US" type="hidden" name="lc"> 
<input type="hidden" name="charset" value="utf-8" />
<input alt="PayPal - The safer, easier way to pay online" type="submit" name="submit"> 
</form>
php;
        }
        return $pay;
    }

    public function cancel() {
        $this->error('Your payment has been cancelled.', url('index/account'));
    }

    public function suc() {
        $res = Db::name('member_pay_log')->whereTime('pay_time', 'today')->find();
        if (!$res)
            $this->error('Illegal request.', url('index/account'));
        else
            $this->success('Your payment has been processed successfully,the window will skip to the home page.', url('index/member'));
    }

    /**
     * 播放视频
     */
    public function void() {
        if ($this->request->isPost()) {
            $level_id = session('member_info.level_id');
            if ($level_id != 1) {
                die(handleResult(1, ''));
            } else {
                die(handleResult(0, 'Please become a paid member first！'));
            }
        }
        
        //获取该用户的所有观看记录
        $play_log = array_reduce(Db::name('play_log')->where(['user_id'=> session('member_info.id')])->select(), function(&$newArray,$v){
            $newArray[$v['void_id']] = $v;
            return $newArray;
        });
      
        return $this->fetch('',[
            'data'=>$play_log
        ]);
    }

    /**
     * 记录会员观看日志
     */
    public function whiteLog() {
        $param = input('param.');
        $user_id = session('member_info.id');

        //拼接用户id+void为 为唯一值缓存起来
        $weiyi = $user_id . $param['void_id'] . date('Y-m-d', time());

        if (!cache($weiyi)) { //不存在就缓存
            //查出用户的观看该视频的时长
            $pay_log = Db::name('play_log')->where(['id' => $user_id, 'void_id' => $param['void_id']])->find();
            if (!$pay_log) {

                $array = [
                    'user_id' => $user_id,
                    'void_id' => $param['void_id'],
                    'seconds' => $param['seconds'],
                    'percent' => $param['percent'],
                    'duration' => $param['duration'],
                    'add_time' => date('Y-m-d H:i:s', time()),
                    'complete_time' => date('Y-m-d H:i:s', time())
                ];
                $pay_id = Db::name('play_log')->insertGetId($array);
                if (!$pay_id) {
                    $this->error('观看记录增加失败！');
                }
                $pay_log = Db::name('play_log')->find($pay_id);
            }

            //缓存
            cache($weiyi, $pay_log);
        } else {
            $hc_pay_log = cache($weiyi);

            //如果完成了就删除
            if ($hc_pay_log['percent'] == 1) {
                return;
            }

            if ($hc_pay_log['percent'] > $param['percent']) {
                return;
            } else {
                //如果已经完成了
                if ($hc_pay_log['percent'] > 0.999) {
                    $array = [
                        'id' => cache($weiyi)['id'],
                        'percent' => 1,
                        'complete_time' => date('Y-m-d H:i:s', time())
                    ];
                    Db::name('play_log')->update($array);
                    $hc_pay_log['percent'] = 1; // 更新时长完成
                    //更新缓存
                    cache($weiyi, $hc_pay_log);
                } else {
                    $array = [
                        'id' => cache($weiyi)['id'],
                        'seconds' => $param['seconds'],
                        'percent' => $param['percent'],
                        'duration' => $param['duration']
                    ];
                    Db::name('play_log')->update($array);
                    $hc_pay_log['percent'] = $param['percent']; // 更新看过的时长
                    //更新缓存
                    cache($weiyi, $hc_pay_log);
                }
            }
        }
    }

}
